<template>
  <div class="edu-page-warp">
    <el-card shadow="never" body-style="padding: 24px;" class="card-margin">
        <h1 class="condition-title">基本信息</h1>
      <div>
        <span class="text-light-gray">申请编号：{{ rollInfo.no }}</span>
      </div>
      <div class="edu-detail-title"></div>
      <el-row style="margin:10px 0">
        <el-col :span="6"><span class="text-light-gray">申请人：</span><span>{{ user.name }}</span></el-col>
        <el-col :span="6"><span class="text-light-gray">学院：</span>{{departmentName}}</el-col>
        <el-col :span="6"><span class="text-light-gray">导师：</span>{{ user.teacherName }}</el-col>
        <el-col :span="6"><span class="text-light-gray">申请日期：</span><span>{{ approvalInfo.time|formatDate }}</span></el-col>
      </el-row>
    </el-card>
    <el-card shadow="never" body-style="padding: 24px;" class="card-margin">
      <h1 class="condition-title">申请明细</h1>
      <el-row :gutter="20" class="edu-info-list">
        <el-col>
          <div class="item-group" style="width: 100%">
              <label class="secondary-text label">审批类型：</label>
              <div class="display-inline-block" style="width: 50%">
                <span class="majoy-text span">培养计划
                </span>
              </div>
          </div>
          </el-col>
      </el-row>
      <el-row :gutter="20" class="edu-info-list">
        <el-col>
          <div class="item-group" style="width: 100%">
              <label class="secondary-text label">审批内容：</label>
              <div class="display-inline-block" style="width: 50%">
                <a class="majoy-text span bold" style="text-decoration:underline;cursor:pointer"  @click="showCulturePlan">{{major}}{{$t("culturePlan.culturePlan")}}
                </a>
              </div>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="edu-info-list">
        <el-col>
            <div class="item-group" style="width: 100%">
              <label class="secondary-text label">审批说明：</label>
              <div class="display-inline-block" style="width: 50%">
                <span class="majoy-text" style="width: 100%">
                  <el-input
                    :rows="3"
                    v-model="approvalInfo.content"
                    :disabled="rollInfo.result != 'Process'"
                    type="textarea"
                    placeholder="请输入内容"
                    style="width: 100%;min-height: 80px;"/>
                </span>
              </div>
            </div>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="edu-info-list">
        <el-col>
          <div class="item-group" style="width: 100%">
            <label class="secondary-text label">附件上传：</label>
            <div class="display-inline-block">
              <el-upload
                :headers="{'X-Token': $store.state.session.sessionid}"
                :data="{bucketname: 'face', folderpath: 'file'}"
                :on-preview="handleAvatarPreview"
                :on-remove="handleAvatarRemove"
                :on-success="handleAvatarSuccess"
                :disabled="rollInfo.result != 'Process'"
                class="upload-demo"
                action="/api/commonservice/obsfile/uploadfile"
                multiple>
                <el-button
                  :disabled="rollInfo.result != 'Process'"
                  size="small"
                  type="primary">选择文件</el-button>
                  <span  class="el-upload__tip">您可以上传图片或文档，大小不要超过3MB</span>                 
              </el-upload>
            </div>
          </div>
        </el-col>
      </el-row>
      <div class="edu-opertion-bar">
        <div class="float-right">
          <el-button
            :disabled="rollInfo.result != 'Process'"
            type="danger"
            @click="submiteReject">驳回</el-button>
          <el-button
            :disabled="rollInfo.result != 'Process'"
            type="primary"
            @click="submiteThrough">通过</el-button>
        </div>
    </div>
    </el-card>    
    <el-card shadow="never" body-style="padding: 24px;" class="card-margin">
      <h1 class="condition-title">审批进度</h1>
      <el-table :data="rollInfo.listApproveHistory" stripe style="width: 100%">
        <el-table-column
          prop="id"
          label="序号"
          width="80"
        />
        <el-table-column
          prop="time"
          label="时间"
          width="160"
        >
          <template slot-scope="scope">
            {{ scope.row.time | formatDate }}
          </template>
        </el-table-column>
        <el-table-column
          prop="approvorName"
          label="审批人"
          width="120"
        />
        <!-- <el-table-column
          prop="groupStr"
          label="角色"
          width="120"
        /> -->
        <el-table-column
          prop="role"
          label="角色"
          width="120"
        />
        <el-table-column
          prop="result"
          label="审批结果"
          width="120"
        >
          <template slot-scope="scope">
            <el-tag
              v-if="scope.row.result == 'Process'"
              type="success"
            >进行中</el-tag>
            <el-tag
              v-if="scope.row.result == 'End'"
              type="info"
            >已结束</el-tag>
            <el-tag
              v-if="scope.row.result == 'Reject'"
              type="warning"
            >已驳回</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="content"
          label="审批说明"
        />
        <el-table-column
          prop="fileInfo"
          label="审批材料"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.fileInfo">
              <el-button
                v-for="item in scope.row.fileInfo.approveAttachment"
                :key="item"
                type="text"
                @click="handleGetFile(item)"
              >{{ item }}</el-button>
              <!-- <span>{{scope.row.fileInfo}}</span> -->
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog title="个人培养计划" width="80%" :visible.sync="showCulturePlanDialog" :close-on-click-modal="false"
            :close-on-press-escape="false">
        <personPlanDetail :student-id='approvalInfo.uid' :approveDetail='approveDetail' read-only=true />
    </el-dialog>
  </div>
</template>
<script>
import {
  selectApproFlow,
  approvalThrough,
  approvalReject
} from "common/src/api/approval";
import { findUserInfoByIdType, findLocalUserById } from "common/src/api/user";
import { schemePlanAddSet, schemePlanfindResult } from "common/src/api/culture/culturePlan";
import { downloadfile } from "common/src/api/upload";
import filters from "common/src/filters";
import personPlanDetail from './personalPlanDetail'
import { mapActions } from 'vuex'

export default {
  name: "approveDetail",
  props: {
        publicInfo: {
          type: Object,
          default: {}
       }
  },
  components: {
    personPlanDetail
  },
  filters: {
    formatDate(date) {
      return filters.formatDate(date, "yyyy/MM/dd hh:mm:ss");
    }
  },
  data() {
    return {
      id: "",
      rollInfo: [],
      user: {},
      approvalInfo: {
        uid:'',
        no: "",
        content: "",
        approveAttachment: [],
        approveDoc: [],
        remark: null,
      },
      cultureName:'',
      departmentName:'',
      major:'',
      showCulturePlanDialog:false,
      approveDetail:true
    };
  },
  mounted() {
    this.id = this.$route.query.id;
    if (this.publicInfo && this.publicInfo.no) {
        this.id = this.publicInfo.no;
    }
    this.initPage(this.id);
    this.getTime()
  },
  methods: {
    ...mapActions(['delTab']),
    _init_(user) {
      const query = "userId=" + user.uid + "&type=" + user.type;
      findUserInfoByIdType(query).then(res => {
        if (res.code === 200 && res.data) {
          res.data.userType = user.type;
          this.user = res.data;
        }
      });
    },
    _initLocalUser(uid) {
      findLocalUserById("userId=" + uid).then(res => {
        if (res.code === 200 && res.data) {
          this.user = res.data;
          this.user.name = res.data.userName;
        }
      });
    },
    initPage(id) {
      selectApproFlow(id).then(res => {
        if (res && res.data) {
          const _user = {
            uid: res.data.applicantId,
            type: res.data.userType ? res.data.userType : "2"
          };

          if (res.data.userType === "3") {
            this._initLocalUser(_user.uid);
          } else {
            this._init_(_user);
          }
          this.approvalInfo.uid=res.data.applicantId;
          this.approvalInfo.no = res.data.no;
          this.approvalInfo.time=res.data.time;
          console.log(res.data.content);
          let result=JSON.parse(res.data.content);
          if(result&&result.cultureName){
            this.cultureName=result.cultureName;
          }
          if(result&&result.departmentId){
            this.departmentName=result.departmentId;
          }
          if(result&&result.major){
            this.major=result.major;
          }
          let listApproveHistory = res.data.listApproveHistory
          if(listApproveHistory.length > 0){
            listApproveHistory.forEach(d =>{
              if(d.fileInfo){
                d.fileInfo = JSON.parse(d.fileInfo)
              }
            })
          }
          this.rollInfo = res.data;
          if (this.publicInfo && this.publicInfo.no) {
               this.rollInfo.result = this.publicInfo.result; 
          }
        }
      });
    },
    getTime(){
        // let currentUser =
        //     (this.$store.state.session && this.$store.state.session.user) ||
        //     JSON.parse(localStorage.getItem("user"));
        let data = {
            grade: "", // 年级
            deptCode: "", // 学院
            startTime: "", // 开始时间
            stopTime: "", // 结束时间
            projId:"",
            projIdStr:this.$route.query.projId
        }
        if (this.publicInfo && this.publicInfo.content) {
            data.projIdStr = this.publicInfo.content.projId;
        }
        schemePlanfindResult(data).then(res =>{
            if(res.code == 200){
                this.approvalInfo.startTime = res.data.startTime
                this.approvalInfo.endTime = res.data.stopTime    
            }
        })
    },
    handleGetFile(objectkey) {
      if (!objectkey) return;
      downloadfile(objectkey);
    },
    handleAvatarRemove(file, fileList) {
        const removeFile = file.response.data[file.name].objectkey;
        _.remove(this.approvalInfo.approveAttachment, function(item) {
            return item === removeFile;
        });
        _.remove(this.approvalInfo.approveDoc, function(item) {
            return item.fileLacation === removeFile;
        });
    },
    handleAvatarSuccess(response, file, fileList) {
        if (response && response.data) {
            this.approvalInfo.approveDoc.push({
                fileName: response.data[file.name].fileName,
                fileLacation: response.data[file.name].objectkey
            });
            this.approvalInfo.approveAttachment.push(
                response.data[file.name].objectkey
            );
        }
    },
    showCulturePlan(){
      this.showCulturePlanDialog=true;
    },
    submiteThrough(){
      let now = new Date().getTime();
      console.log(now)
      if(now > this.approvalInfo.endTime || now < this.approvalInfo.startTime){
          this.$message({
              type: "warning",
              message: "不在审批范围时间内"
          });
          return;
      }else{
        approvalThrough(this.approvalInfo).then(res => {
          this.delTab('/approveDetail');
          window.history.back();
        })
      }
      
    },
    submiteReject(){
        let now = new Date().getTime();
        if(now > this.approvalInfo.endTime || now < this.approvalInfo.startTime){
          this.$message({
              type: "warning",
              message: "不在审批范围时间内"
          });
          return;
        }else{
          approvalReject(this.approvalInfo).then(res => {
            this.delTab('/approveDetail')
            window.history.back();
          })
        }
    }
  }
};
</script>
<style scoped>
    .div-main {
        margin-bottom: 16px;
    }
    .bold{
      font-weight: bold;
    }

</style>